# coding=utf-8
import re

from learning.scientifc import writer
from learning.scientifc.jobs.job import Job
from learning.scientifc.readers.reader import ReaderFactory
from learning.scientifc.utils import money_utils


class ExtractNumbersJob(Job):
    name = '提取 Excel 金额数额'

    def __init__(self, app):
        super().__init__(app)
        self.src_column_index = app.config.get('EXTRACT_NUMBERS_SRC_COLUMN_INDEX')
        self.filename = app.config.get('EXTRACT_NUMBERS_FILENAME')
        self.reader_factory = ReaderFactory(app)
        self.condition_words = ['赔偿']
        self.res = [
            re.compile('([一二三四五六七八九〇十百千万亿]*?)(元|百万|万元|亿元|万|亿|角|分)'),
            re.compile('([壹贰叁肆伍陆柒捌玖零拾佰仟萬億]*?)(元|百万|万元|亿元|万|亿|角|分)'),
            re.compile('([１２３４５６７８９０]*?)(元|百万|万元|亿元|万|亿|角|分)'),
            re.compile('(\d*[\d,，]*\.?\d*)(元|百万|万元|亿元|万|亿|角|分)'),
            re.compile('(0\.\d+)(元|百万|万元|亿元|万|亿|角|分)')
        ]

    def cut(self, line):
        return re.split('[。；，]', line)

    def is_satisfy_condition(self, sentence):
        for condition in self.condition_words:
            if condition in sentence:
                return True
        return False

    def convert_to_numbers(self, raw_list):
        result = 0
        for raw in raw_list:
            result += money_utils.convert_to_number(raw)
        return result

    def run(self, *args, **kwargs):
        reader = self.reader_factory.create(self.filename)
        all_money = []
        all_money_amount = []
        header = reader.row_values(0)
        for i, data in reader.range(1):
            source = data[self.src_column_index]
            money_per_row = []
            money_amount_per_row = []
            for sentence in self.cut(source):
                if not self.is_satisfy_condition(sentence):
                    continue

                for r in self.res:
                    result = r.findall(sentence)
                    if result:
                        for content in result:
                            if content[0]:
                                join = ''.join(content)
                                money_per_row.append(join)
                                money_amount_per_row.append(join.replace('元', '').replace('角', '').replace('分', ''))

            money_per_row = ', '.join([i for i in money_per_row if i])
            all_money_amount.append(self.convert_to_numbers(money_amount_per_row))
            all_money.append(money_per_row)

        # 写入文件
        write_data = [tuple(header + ['总结', '源数据'])]
        for i, data in reader.range(1):
            write_data.append(tuple(data + [all_money_amount[i - 1]] + [all_money[i - 1]]))
        writer.write(write_data)
